(function(){
	angular.module('app')
	.directive('myLoading', ['$compile', function( $compile ){
		var loadingTemplate =  "" +
			"<div class=\"loader\">\n" +
	      	"  <div class=\"loader-content\" style=\"position: absolute;top: 50%;left: 50%; margin : -15px 0 0 -15px; \">\n" +
	      	"	<img style=\"width:30px;\" ng-show=\"loadingImg\" ng-src=\"{{loadingImg}}\">\n" +
	      	"  </div>\n" +
	     	 "</div>";
		return {
			restrict : 'AE',
			scope : {
				myLoading : '=',
				message : '=',
				src : '='
			},
			link : function( scope, element, attrs ){
				scope.message = scope.message || '';
				scope.loadingImg = '../assets/images/mxu/loading.gif';
				scope.$watch( 'myLoading', function( loading ){
					if( typeof loading === 'undefined' ){
						return false;
					}
					if( loading ){
						element.triggerHandler('loading');
					}else{
						element.triggerHandler('destroy');
					}
				} );
				
				element.on({
					_create : function( event, cssInfo ){
						this.loading = $( loadingTemplate ).appendTo( 'body' )
							.css({
								position : 'absolute',
								width : cssInfo['width'] + 'px',
			                    height : cssInfo['height'] + 'px',
			                    left : cssInfo['left'] + 'px',
			                    top : cssInfo['top'] + 'px',
			                    'z-index' : cssInfo['z-index'] > 1050 ? cssInfo['z-index'] : 1050,
			                    'display' : 'inline-block'
							});
						$compile( this.loading.contents() )( scope );
					},
					loading : function(){
						var cssInfo = {};
						$.extend( cssInfo, element.offset() );
						cssInfo['width'] = element.outerWidth();
		                cssInfo['height'] = element.outerHeight();
		                cssInfo['z-index'] = element.css('z-index');
		               	element.triggerHandler('_create', [cssInfo]);
					},
					
					destroy : function(){
						this.loading && this.loading.remove();
						this.loading = null;
						setTimeout(function(){
							$('body').find('.loader').length && $('body').find('.loader').remove();
						}, 200);
					}
				})
			},
		}
	}]);
})();